package common

import (
	"bytes"
	"io/ioutil"
	"unicode/utf8"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

//	将 UTF8 字符串转换为 GBK 字符串
func toGBK(src string) ([]byte, error) {
	return ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(src)), simplifiedchinese.GB18030.NewEncoder()))
}

func CompareByPinyin(left, right string) bool {
	si, _ := toGBK(left)
	sj, _ := toGBK(right)
	for k, ci := range si {
		if k >= len(sj) {
			return false
		}
		if ci != sj[k] {
			//	比较不同字符
			return ci < sj[k]
		}
	}
	return true
}

func CompareByLengthAndPinyin(left, right string) bool {
	//	长度倒序、名称正序
	li := utf8.RuneCountInString(left)
	lj := utf8.RuneCountInString(right)
	if li == lj {
		// 比较拼音
		return CompareByPinyin(left, right)
	}
	//	比较长度
	return li > lj
}
